/*
 * @Author: Troubadour 2276791354@qq.com
 * @Date: 2024-04-28 17:51:03
 * @LastEditors: Troubadour 2276791354@qq.com
 * @LastEditTime: 2024-04-29 09:29:15
 * @Version:
 * @Description:
 */

#include "drv_spi.h"
#include "spi_flash_sfud.h"
#include "fal.h"


#define W25Q32_CS_GPIOx         GPIOB
#define W25Q32_CS_PIN           GPIO_PIN_12

rt_spi_flash_device_t rtt_spi_dev = RT_NULL;


int W25Q32_Init(void)
{
    /* Step1. 绑定片选引脚，也就是绑定设备。spi20 表示挂载在 spi2 总线上的 0 号设备, PB12是片选，这一步就可以将从设备挂在到总线中 */
    if (rt_hw_spi_device_attach("spi2", "spi20", GPIOB, GPIO_PIN_12) != RT_EOK)
    {
        LOG_E("SPI device attach failed! ");
        return -1;
    }

    /* 通过SFUD（串行闪存通用驱动程序）驱动程序库和SPI设备探测SPI FLASH设备。 */
    rtt_spi_dev = rt_sfud_flash_probe("W25Q32", "spi20");
    if (rtt_spi_dev == RT_NULL)
    {
        LOG_E("sfud flash probe failed! ");
        return -1;
    }

    /* ------------------------------------- */
    /* Step2. FAL initialization.            */
    /* ------------------------------------- */
    fal_init();
    LOG_D("W25Q32 ready! ");

    return 0;
}

INIT_COMPONENT_EXPORT(W25Q32_Init);


const rt_uint8_t TestWriteString[] = "Hello! This is test content.";
void W25Q32_WriteStr(int argc, char **argv)
{
    rt_uint32_t WriteCount = 0;

    /* Step1. Erase to Flash */
    LOG_I("Run W25Q32 Erase.");
    WriteCount = fal_partition_erase(fal_partition_find("easyflash"), 0, 4096);
    if (WriteCount <= 0)
    {
        LOG_E("fal_partition_write failed! ");
    }
    else
    {
        LOG_I("fal_partition_write succeess! Write size: %d", WriteCount);
    }

    /* Step2. Write to Flash */
    LOG_I("Run W25Q32 WriteStr.");
    WriteCount = fal_partition_write(fal_partition_find("easyflash"), 0, TestWriteString, sizeof(TestWriteString));
    if (WriteCount <= 0)
    {
        LOG_E("fal_partition_write failed! ");
    }
    else
    {
        LOG_I("fal_partition_write succeess! Write size: %d", WriteCount);
    }
}


void W25Q32_ReadStr(int argc, char **argv)
{
    rt_uint32_t ReadCount = 0;
    uint8_t ReadBuff[128] = {0};

    /* Step1. Read data from Flash */
    LOG_I("Read W25Q32 data.");
    ReadCount = fal_partition_read(fal_partition_find("easyflash"), 0, ReadBuff, sizeof(ReadBuff));
    if (ReadCount != sizeof(ReadBuff))
    {
        LOG_E("fal_partition_read failed! ");
    }
    else
    {
        LOG_I("fal_partition_read succeess! Read size: %d", ReadCount);
        LOG_I("Read data: %s", ReadBuff);
    }
}

MSH_CMD_EXPORT(W25Q32_WriteStr, Run W25Q32 WriteStr);
MSH_CMD_EXPORT(W25Q32_ReadStr, Run W25Q32 ReadStr);



































